import * as vscode from "vscode";
import { MirServerProvider } from "./extension";

export class CustomLanguageFormatter implements vscode.DocumentFormattingEditProvider {
  // 首尾空白正则（包含换行）
  private readonly TRIM_REGEX = /^[\s\n]+|[\s\n]+$/g;
  // 标签正则 [xxx]
  private readonly TAG_REGEX = /\[[^$$]+\]/g;

  provideDocumentFormattingEdits(document: vscode.TextDocument, options: vscode.FormattingOptions, token: vscode.CancellationToken): vscode.TextEdit[] {
    // const text = document.getText();
    const edits: vscode.TextEdit[] = [];

    // 1. 处理首尾空白
    // this.handleTrim(text, document, edits);

    // 2. 处理标签间距
    // this.handleTagsSpacing(text, document, edits);

    return edits;
  }

  /**
   * 处理首尾空白
   */
  private handleTrim(text: string, document: vscode.TextDocument, edits: vscode.TextEdit[]) {
    // 首部空白
    // const startMatch = text.match(/^[\s\n]+/);
    // if (startMatch) {
    //   const range = new vscode.Range(document.positionAt(0), document.positionAt(startMatch[0].length));
    //   edits.push(vscode.TextEdit.replace(range, ""));
    // }
    // 尾部空白
    const endMatch = text.match(/[\s\n]+$/);
    if (endMatch && endMatch.index !== undefined) {
      const startPos = endMatch.index;
      const range = new vscode.Range(document.positionAt(startPos), document.positionAt(text.length));
      edits.push(vscode.TextEdit.replace(range, ""));
    }
  }

  /**
   * 处理标签间距
   */
  private handleTagsSpacing(text: string, document: vscode.TextDocument, edits: vscode.TextEdit[]) {
    let currentIndex = 0;

    while (currentIndex < text.length) {
      const char = text[currentIndex];

      // 发现标签起始符
      if (char === "[" && text[currentIndex + 1] !== "[") {
        const tagEndIndex = text.indexOf("]", currentIndex);

        if (tagEndIndex > 0) {
          // 标签前后检查换行
          this.ensureNewlineBefore(document, text, currentIndex, edits);
          this.ensureNewlineAfter(document, text, tagEndIndex, edits);

          currentIndex = tagEndIndex + 1;
          continue;
        }
      }

      currentIndex++;
    }
  }

  /**
   * 确保标签前有换行
   */
  private ensureNewlineBefore(document: vscode.TextDocument, text: string, position: number, edits: vscode.TextEdit[]) {
    if (position === 0) {
      return;
    }

    // 检查前一个字符是否是换行
    if (text[position - 1] !== "\n") {
      const range = new vscode.Range(document.positionAt(position), document.positionAt(position));
      edits.push(vscode.TextEdit.replace(range, "\n"));
    }
  }

  /**
   * 确保标签后有换行
   */
  private ensureNewlineAfter(document: vscode.TextDocument, text: string, position: number, edits: vscode.TextEdit[]) {
    if (position === text.length - 1) {
      return;
    }

    // 检查后一个字符是否是换行
    if (text[position + 1] !== "\n") {
      const range = new vscode.Range(document.positionAt(position + 1), document.positionAt(position + 1));
      edits.push(vscode.TextEdit.replace(range, "\n"));
    }
  }
}

export class MirtxtLanguageFormatter implements MirServerProvider {
  activate() {
    vscode.languages.registerDocumentFormattingEditProvider("mirtxt", new CustomLanguageFormatter());
  }
}
